package oppsa.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Vector;

import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

import oppsa.controller.Properties;
import oppsa.controller.Translate;
import oppsa.controller.User;
import oppsa.model.ProjectDB;
import oppsa.model.UserDB;
import oppsa.util.ConnectionFactory;
import oppsa.util.Constants;
import oppsa.util.FileChooser;
import oppsa.util.InterfaceConnection;
import oppsa.util.MailSMTP;
import oppsa.util.Session;

import org.jdesktop.swingx.JXFrame;

public class AuthentificationView extends JXFrame {
	
	public JLabel userLabel;
	public JTextField userText;
	public JLabel lblPassword;
	public JPasswordField passwordText;
	public JButton loginButton;
	public JButton btnRegister;
	private Translate t = new Translate();
	private JPanel contentPane;
	private JPasswordField passwordField;
	private JLabel lblNewUser;
	private JLabel lblMissingPassword;
	private JLabel lblauthError; 
	private JRadioButton radioLocal;
	private JRadioButton radioDistant;
	private final ButtonGroup group = new ButtonGroup();
	private JLabel lblForgotAccount;
	private JLabel lblCobalt;
	private JButton btnForgotPass;
	private JButton btnForgotAccount;
	private JButton btnNewPortfolio;
	private JComboBox<String> portfolioComboBox;
	private Properties prop;
	private JLabel lblUser;
	private DefaultComboBoxModel<String> model;
	
	
	public AuthentificationView(){
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
		} catch (ClassNotFoundException e1) {

			System.err.println("Ops : "+ e1.getMessage());
		} catch (InstantiationException e1) {

			System.err.println("Ops : "+ e1.getMessage());
		} catch (IllegalAccessException e1) {

			System.err.println("Ops : "+ e1.getMessage());
		} catch (UnsupportedLookAndFeelException e1) {

			System.err.println("Ops : "+ e1.getMessage());
		}
		setIconImage(Toolkit.getDefaultToolkit().getImage(HomeView.class.getResource("/LOGO_FONCE.png")));
		
		passwordField = new JPasswordField();
		getRootPaneExt().getContentPane().add(passwordField, BorderLayout.NORTH);
		Session.typeConnexion= t.getLocalizedText("local_type");
		Session.connexion=Constants.HSQLDB;
		prop = new Properties();
    	prop.loadProperties(Constants.config_path);
    	prop.setProperties("path", System.getProperty("user.dir"),Constants.config_path);
	}
	
	public void placeComponents() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 426, 357);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		lblUser = new JLabel("User");
		lblUser.setBounds(27, 47, 113, 24);
		contentPane.add(lblUser);
		
		userText = new JTextField(20);
		userText.setBounds(189, 47, 172, 24);
		contentPane.add(userText);
		userText.addKeyListener(new KeyAdapter() {
            @Override
			public void keyReleased(KeyEvent e) {
            	int key=e.getKeyCode();
            	if(key==KeyEvent.VK_ENTER)
                { 
            		if(portfolioComboBox.getSelectedItem().toString() != null){
    					//if(radioLocal.isSelected() || radioDistant.isSelected()){
						prop.setProperties("BDD", portfolioComboBox.getSelectedItem().toString(),Constants.config_path);
						Session.currentBDD=prop.getProperties().getProperty("BDD");
						login();
					//}
					} else {
						lblauthError.setText(t.getLocalizedText("lblPorfolioError"));
					}
					//lblauthError.setText(t.getLocalizedText("lblauthError"));
                }
            }
		});

		passwordText = new JPasswordField();
		passwordText.setBounds(189, 82, 172, 24);
		contentPane.add(passwordText);
		passwordText.addKeyListener(new KeyAdapter() {
            @Override
			public void keyReleased(KeyEvent e) {
            	int key=e.getKeyCode();
            	if(key==KeyEvent.VK_ENTER)
                { 
            		if(portfolioComboBox.getSelectedItem().toString() != null){
    					//if(radioLocal.isSelected() || radioDistant.isSelected()){
						prop.setProperties("BDD", portfolioComboBox.getSelectedItem().toString(),Constants.config_path);
						Session.currentBDD=prop.getProperties().getProperty("BDD");
						login();
					//}
					} else {
						lblauthError.setText(t.getLocalizedText("lblPorfolioError"));
					}
					//lblauthError.setText(t.getLocalizedText("lblauthError"));
                }
            }
		});
		lblPassword = new JLabel(t.getLocalizedText("lblPassword"));
		lblPassword.setBounds(27, 82, 113, 24);
		contentPane.add(lblPassword);
		
		JSeparator separator = new JSeparator();
		separator.setBounds(10, 222, 390, 2);
		contentPane.add(separator);
		
		lblNewUser = new JLabel(t.getLocalizedText("lblNewUser"));
		lblNewUser.setBounds(27, 293, 192, 14);
		contentPane.add(lblNewUser);
		
		loginButton = new JButton(t.getLocalizedText("loginButton"));
		loginButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(!userText.getText().equals("") &&  !passwordText.getPassword().equals("")){
					if(portfolioComboBox.getSelectedItem() != null){
					//if(radioLocal.isSelected() || radioDistant.isSelected()){
						prop.setProperties("BDD", portfolioComboBox.getSelectedItem().toString(),Constants.config_path);
						Session.currentBDD=prop.getProperties().getProperty("BDD");
						login();
					//}
					} else {
						lblauthError.setText(t.getLocalizedText("lblPorfolioError"));
					}
				}
				//lblauthError.setText(t.getLocalizedText("lblauthError"));
			}
		});
		loginButton.setBounds(300, 127, 100, 23);
		contentPane.add(loginButton);
		
		btnRegister = new JButton(t.getLocalizedText("registerButton"));
		btnRegister.setBounds(240, 290, 160, 23);
		contentPane.add(btnRegister);
		
		lblMissingPassword = new JLabel("<html><u>"+t.getLocalizedText("forgetpass")+"</u></html>");
		lblMissingPassword.setBounds(27, 262, 136, 14);
		contentPane.add(lblMissingPassword);
		
		lblMissingPassword.setCursor(new Cursor(Cursor.HAND_CURSOR));
		
		/*JLabel lblChooseCon = new JLabel(t.getLocalizedText("utilisation"));
		lblChooseCon.setBounds(27, 161, 62, 14);
		contentPane.add(lblChooseCon);
		
		radioLocal = new JRadioButton(t.getLocalizedText("utilisationLocal"));
		radioLocal.setSelected(true);
		radioLocal.setBounds(147, 157, 109, 23);
		contentPane.add(radioLocal);
		
		radioDistant = new JRadioButton(t.getLocalizedText("utilisationDistante"));
		radioDistant.setBounds(273, 157, 109, 23);
		contentPane.add(radioDistant);
		//Group the radio buttons.

	    group.add(radioLocal);
	    group.add(radioDistant);*/
	    
	    lblauthError = new JLabel();
	    lblauthError.setForeground (Color.red);
	    lblauthError.setBounds(147, 11, 224, 23);
	    contentPane.add(lblauthError);
	    
	    JLabel choosePortfolio = new JLabel(t.getLocalizedText("lblChoosePortfolio"));
	    choosePortfolio.setBounds(27, 152, 152, 24);
	    contentPane.add(choosePortfolio);
	    
	    
	    Vector<String> comboBoxItems=new Vector<String>();
	    File folder = new File(prop.getProperties().getProperty("path")+"/bdd");
	    File[] listOfFiles = folder.listFiles();

		for (int i = 0; i < listOfFiles.length; i++) {
			if (listOfFiles[i].isFile() && (listOfFiles[i].getName().endsWith(".script"))) {
				comboBoxItems.add(listOfFiles[i].getName().replaceFirst("[.][^.]+$", ""));
			}
		}
	    model = new DefaultComboBoxModel<String>(comboBoxItems);
	    portfolioComboBox = new JComboBox<String>(model);
	    portfolioComboBox.setBounds(37, 187, 192, 24);
	    portfolioComboBox.setSelectedItem(prop.getProperties().getProperty("BDD"));
	    contentPane.add(portfolioComboBox);
	    
	    JButton btnImportButton = new JButton("Import");
	    btnImportButton.setBounds(300, 188, 100, 23);
	    contentPane.add(btnImportButton);
	    
	    lblForgotAccount = new JLabel(t.getLocalizedText("lblForgotAccount"));
	    lblForgotAccount.setBounds(27, 229, 136, 23);
	    contentPane.add(lblForgotAccount);
	    
	    lblCobalt = new JLabel("Cobalt");
	    lblCobalt.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 15));
	    lblCobalt.setBounds(72, 11, 52, 25);
	    contentPane.add(lblCobalt);
	    
	    btnForgotAccount = new JButton(t.getLocalizedText("btnForgotAccount"));
	    btnForgotAccount.setBounds(240, 227, 160, 23);
	    contentPane.add(btnForgotAccount);
	    
	    btnForgotPass = new JButton(t.getLocalizedText("btnForgotPass"));
	    btnForgotPass.setBounds(240, 259, 160, 23);
	    contentPane.add(btnForgotPass);
	    
	    btnNewPortfolio = new JButton("");
	    btnNewPortfolio.setBounds(240, 188, 30, 23);
	    btnNewPortfolio.setIcon(new ImageIcon(getClass().getResource(t.getLocalizedText("PlusBS"))));
	    btnNewPortfolio.setBorder(null);
	   
	    contentPane.add(btnNewPortfolio);
		/*
	    //Register a listener for the radio buttons.
	    radioDistant.addActionListener(new ActionListener() {
	    	   @Override
			public void actionPerformed(ActionEvent e) {
	    	    Session.connexion=Constants.MYSQL;
	    	    Session.typeConnexion= t.getLocalizedText("shared_type");
	    	    //temporaire
	    	    Session.currentBDD="cobaltdb";
	   	    }
	    });
	    radioLocal.addActionListener(new ActionListener() {
	    	   @Override
			public void actionPerformed(ActionEvent e) {
    		   	Session.connexion=Constants.HSQLDB;
    		   	Session.typeConnexion= t.getLocalizedText("local_type");
    		   	//Temporaire
    		   	Session.currentBDD="cobaltdb";
	   	    }
	    });
	    */

	    
		lblMissingPassword.addMouseListener(new MouseAdapter() {
			 @Override
			public void mouseReleased(MouseEvent e)  
			    {  
 
			        	UserDB userDB = new UserDB();
			        	User user = userDB.selectByLogin(userText.getText());
			        	if(user!=null){
			        		
			    			try {
			    				MailSentDialog dialog = new MailSentDialog(user.getMail());
			    				dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			    				dialog.setVisible(true);
			    			} catch (Exception e2) {
			    				e2.printStackTrace();
			    			}
				        	
				        	MailSMTP mail = new MailSMTP();
				    		try {
				    			String mess = t.getLocalizedText("hello") +" "+ user.getLogin() + "," +
				                        "\n "+t.getLocalizedText("voicipassword")+" : " + user.getPassword() +
				                        "\n\n "+t.getLocalizedText("cordialement");
				    			mail.sendmail(user.getMail(), mess);
	
				    		} catch (Exception e1) {

				    			e1.printStackTrace();
				    		}
			        	} else {
			        		try {
			    				MailSentDialog dialog = new MailSentDialog(false);
			    				dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			    				dialog.setVisible(true);
			    			} catch (Exception e2) {
			    				e2.printStackTrace();
			    			}
			        	}
	 
			    }  
		});
		
		btnImportButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
								
				FileChooser fs = new FileChooser();
				File f = fs.openFile();
				if(f != null){
					model.addElement(f.getName().replaceFirst("[.][^.]+$", ""));
				}
			}
		});
		
		btnRegister.addActionListener(new ActionListener() {
			@Override
		public void actionPerformed(ActionEvent e) {
							
			
			try {

			     String url ="http://my-cobalt.net/Client/fr/telechargement.aspx";

				     Desktop dt = Desktop.getDesktop();
				     URI uri = new URI(url);
				     dt.browse(uri.resolve(uri));


				 } catch (URISyntaxException ex) {

				 } catch (IOException ex) {

				 }
			}
		});
		
		 btnNewPortfolio.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				JXFrame addPortfolio = new AddPortfolio(AuthentificationView.this);
				setEnabled(false);
				addPortfolio.setVisible(true);
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				JButton source = (JButton) e.getSource();
				source.setIcon(new ImageIcon(getClass().getResource(t.getLocalizedText("PlusB"))));
			}

			@Override
			public void mouseExited(MouseEvent e) {
				JButton source = (JButton) e.getSource();
				source.setIcon(new ImageIcon(getClass().getResource(t.getLocalizedText("PlusBS"))));
			}
		});
	}
	
	private void login(){
		System.out.println(Session.connexion);
		InterfaceConnection cnx = ConnectionFactory.getConnection(Session.connexion);
		Boolean connexion1 = cnx.connectOpenCheck();
		cnx.connectClose();
		
		
		
		if (connexion1)
		{
			UserDB userDB = new UserDB();
			//User user = userDB.selectBySeq(Integer.valueOf(userText.getText()));
			
			User user = userDB.selectByLoginMpd(userText.getText(), passwordText.getPassword());
			if (user != null){
				ProjectDB testProj = new ProjectDB();
				Session.userSequence = user.getSequence();
				int resultTest = testProj.select(Session.userSequence);
	
				dispose();
				if (resultTest==2)
				{
					dispose();
					CreateProjectView createProject = new CreateProjectView();
					
					createProject.setVisible(true);
					
				} else if (resultTest==1) {
	
					Session.projectSequence=testProj.getCurrentProject().getSequence();
					dispose();
					JXFrame homeView = new HomeView();
					homeView.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
					homeView.setVisible(true);
				} else if (resultTest == 3){
	
					dispose();
					ProjectView selectProject = new ProjectView(new HomeView());
					setVisible(false);
					selectProject.setVisible(true);
				}
			} else {
				JOptionPane.showMessageDialog(null, t.getLocalizedText("errorAthentification"));	
			}
		}
		else
		{	

		// html content
		//if(Session.connexion.equals(Constants.MYSQL)){
		
		//} else if(Session.connexion.equals(Constants.HSQLDB)){
			/* ep = new JEditorPane("text/html", "<html><body style=\"" + style + "\">" //
				    + t.getLocalizedText("errorCon11")+" :  <a href=\""+uri+"\">my-cobalt.net</a>" //
				    + "</body></html>");*/
		//}		
		// handle link events
		

		
		// show//
		if(Session.connexion.equals(Constants.MYSQL)){
			JOptionPane.showMessageDialog(null, t.getLocalizedText("errorCon12")+ " at http://my-cobalt.net/Client/fr/contact.aspx");	
		} else if(Session.connexion.equals(Constants.HSQLDB)){
			JOptionPane.showMessageDialog(null, t.getLocalizedText("errorCon11")+ " at http://my-cobalt.net/Client/fr/contact.aspx");	
		}
		}}

	public DefaultComboBoxModel<String> getComboxModel() {
		// TODO Auto-generated method stub
		return model;
	}

}
